/*
 * File     : X86StdCallWindowsNativeCallFactory.java
 * Created  : 21 Apr 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.call;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;

import com.googlecode.dni.internal.DniInternal;
import com.googlecode.dni.internal.library.DynamicLibrary;
import com.googlecode.dni.internal.library.SymbolNotFoundException;
import com.googlecode.dni.library.Function.LastErrorBehaviour;
import com.googlecode.dni.library.Library;
import com.googlecode.dni.type.Pointer;


/**
 * <p>
 *  Implementation of {@link NativeCallFactory} that produces native methods for
 *  calling X86 stdcall Windows methods from X86 Windows.
 * </p>
 *
 * @author Matthew Wilson
 */
public final class X86StdCallWindowsNativeCallFactory extends BaseNativeCallFactory
{

    private static final DynamicLibrary LIBRARY;

    /** JNI function for general case. */
    private static final Pointer CALL;


    static
    {
        LIBRARY = DniInternal.PLATFORM.getDniDynamicLibrary();
        try
        {
            CALL = LIBRARY.getSymbol( "dni_x86_stdcall_windows_call" );
        }
        catch ( Throwable throwable )
        {
            try
            {
                LIBRARY.free();
            }
            catch ( Throwable throwable2 )
            {
                DniInternal.LOGGER.log( Level.SEVERE, "Failed to free library", throwable2 );
            }
            throw new ExceptionInInitializerError( throwable );
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    Pointer getFunctionPointer( final DynamicLibrary dynamicLibrary,
                                final String name,
                                final boolean mangle,
                                final String charset,
                                final List< Parameter > parameters ) throws SymbolNotFoundException
    {
        // try a series of mangled names
        SymbolNotFoundException originalException = null;
        try
        {
            return dynamicLibrary.getSymbol( name );
        }
        catch ( SymbolNotFoundException exception )
        {
            if ( !mangle )
            {
                throw exception;
            }

            originalException = exception;
            DniInternal.LOGGER.log( Level.FINE, "Failed to find: " + name + " ... continuing...", exception );
        }

        // make the stdcall mangled form
        int count = 0;
        for ( Parameter parameter : parameters )
        {
            if ( "ZBSCIF".indexOf( parameter.getNativeType() ) >= 0 )
            {
                count += 4;
            }
            else
            {
                assert "JD".indexOf( parameter.getNativeType() ) >= 0;
                count += 8;
            }
        }
        String stdcallName = "_" + name + "@" + count;

        try
        {
            return dynamicLibrary.getSymbol( stdcallName );
        }
        catch ( SymbolNotFoundException exception )
        {
            DniInternal.LOGGER.log( Level.FINE, "Failed to find: " + name + " ... continuing...", exception );
        }

        // try the A or W form
        String suffix = "A";
        if ( charset.toLowerCase( Locale.US ).contains( "utf-16" ) )
        {
            suffix = "W";
        }
        else if ( Library.DEFAULT_CHARSET.equals( charset ) )
        {
            if ( Charset.defaultCharset().name().toLowerCase( Locale.US ).contains( "utf-16" ) )
            {
                suffix = "W";
            }
        }

        stdcallName += suffix;

        try
        {
            return dynamicLibrary.getSymbol( stdcallName );
        }
        catch ( SymbolNotFoundException exception )
        {
            DniInternal.LOGGER.log( Level.FINE, "Failed to find: " + name + " ... continuing...", exception );
        }

        throw originalException;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    Pointer getNativeBinding( final List< Parameter > returnParameterContainer,
                              final List< Parameter > parameters,
                              final Pointer functionPointer, final LastErrorBehaviour lastErrorBehaviour )
    {
        // TODO v1.1 support varargs
        // TODO v1.1 large parameter support
        // TODO v1.0 structures-by-value

        parameters.add( 0, new FunctionPointerParameter( functionPointer ) );
        parameters.add( 1, new PaddingParameter( 'I' ) );

        return CALL;
    }

}
